package com.jihu.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jihu.mall.common.constant.WareConstant;
import com.jihu.mall.ware.entity.PurchaseDetailEntity;
import com.jihu.mall.ware.entity.WareSkuEntity;
import com.jihu.mall.ware.entity.request.MergeVo;
import com.jihu.mall.ware.entity.request.PurchaseDoneVo;
import com.jihu.mall.ware.entity.request.PurchaseItemDoneVo;
import com.jihu.mall.ware.service.PurchaseDetailService;
import com.jihu.mall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihu.mall.common.utils.PageUtils;
import com.jihu.mall.common.utils.Query;

import com.jihu.mall.ware.dao.PurchaseDao;
import com.jihu.mall.ware.entity.PurchaseEntity;
import com.jihu.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>().eq(PurchaseEntity::getStatus,0).or().eq(PurchaseEntity::getStatus,1)
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //1.新建一个
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());

            this.save(purchaseEntity);
            mergeVo.setPurchaseId(purchaseEntity.getId());
        }

        //TODO 确认采购单状态是0，1才可以合并
        PurchaseEntity byId = this.getById(mergeVo.getPurchaseId());
        List<PurchaseDetailEntity> detailEntities = detailService.listDetailByPurchasedId(byId.getId());
        if(byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
           byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNEND.getCode()){
            List<Long> items = mergeVo.getItems();
            List<PurchaseDetailEntity> collect = items.stream().filter(item ->{
                //先过滤已经分配的采购需求 0，1才可以采购
                PurchaseDetailEntity old = detailService.getById(item);
                if(old.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                   old.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNEND.getCode()){
                    return true;
                }
                return false;
            }).map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item);
                detailEntity.setPurchaseId(mergeVo.getPurchaseId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNEND.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(collect)){
                detailService.updateBatchById(collect);
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setId(mergeVo.getPurchaseId());
                purchaseEntity.setUpdateTime(new Date());
                this.updateById(purchaseEntity);
            }
        }

    }

    /**
     * 采购单id集合
     * @param ids
     */
    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建或已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item ->{
           if(item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                   || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNEND.getCode()) {
               return true;
           }
           return false;
        }).map(item ->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单的状态
        this.updateBatchById(collect);
        //3.改变采购项的状态
        collect.forEach(item ->{
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchasedId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity updateEntity = new PurchaseDetailEntity();
                updateEntity.setId(entity.getId());
                updateEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return updateEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    @Override
    public void done(PurchaseDoneVo vo) {
        //1.改变采购单状态
        List<PurchaseItemDoneVo> items = vo.getItems();
        Boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);

        //2.改变采购项状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}